<!-- 冲红详情 -->
<template>
	<a-modal v-bind="options" wrap-class-name="a-modal-tab-dialog">
		<template #title>
			<div class="a-modal-tab-title" style="height: 56px">
				<a-card
					class="dialog-card-container"
					:tab-list="detailTabs.map((item:any) => ({key: item.key, tab: item.value}))"
					:active-tab-key="activeKey"
					@tabChange="(key:any) => (activeKey = key)" />
			</div>
		</template>

		<div class="flex-container-nomal" style="height: 80vh">
			<div class="flex1 auto-y">
				<a-row style="min-height: 100%">
					<!-- :span="['invoice', 'flush-red'].includes(activeKey) ? 24 : 17" -->
					<a-col
						:span="props.contract?.isApproval && ['invoice', 'flush-red'].includes(activeKey) ? 17 : 24"
						:class="{'contract-information-left': false}">
						<!-- 冲红详情 -->
						<flush-red-details-approval
							:invoiceDetails="invoiceDetails"
							v-if="activeKey == 'flush-red' && invoiceType === 2"
							@close="close"
							:isApproval="props?.contract?.isApproval"></flush-red-details-approval>
						<!-- 开票详情 -->
						<flush-red-invoceing-detail
							v-if="activeKey == 'invoice'"
							v-model:visible="record.showInvoice"
							:invoiceDetails="invoiceDetails"
							@close="close"
							:isApproval="props?.contract?.isApproval" />
						<!-- 申请详情 -->
					</a-col>

					<a-col :span="7" class="approval-process-list-right">
						<approval :processInstanceId="props.contract?.processInstanceId"></approval>
					</a-col>
				</a-row>
			</div>
		</div>

		<template #footer>
			<div v-if="invoiceType === 2 && activeKey === 'flush-red'">
				<!-- 冲红 -->
				<template v-for="(btn, index) in redStatusList[invoiceDetails?.approvalStatus].operation" :key="index">
					<a-button v-if="!props?.contract?.isApproval" :v-action="[btn.action]" @click="handlerClick(btn.field)">
						{{ btn.name }}
					</a-button>
				</template>
				<a-button
					v-if="
						[1, 3].includes(invoiceDetails?.status) &&
						invoiceDetails?.approvalStatus === 3 &&
						hasPermissions(['mk_finance_invoicing_history_red_search']) &&
						!props?.contract?.isApproval
					"
					type="primary"
					@click="handlerClick('queryResults')">
					查询结果
				</a-button>
			</div>

			<div v-if="invoiceType === 1 && activeKey === 'invoice'">
				<!-- 开票 -->
				<a-button
					v-if="
						invoiceDetails?.approvalStatus === 1 &&
						!props?.contract?.isApproval &&
						hasPermissions(['mk_finance_invoicing_history_revoke'])
					"
					@click="submit('revokeApproval')">
					撤销
				</a-button>

				<a-button
					v-if="
						[2, 3, 4].includes(invoiceDetails?.approvalStatus) &&
						[0, 2].includes(invoiceDetails?.status) &&
						hasPermissions(['mk_finance_invoicing_history_cancel']) &&
						!props?.contract?.isApproval
					"
					@click="submit('approveCancel')">
					作废
				</a-button>
				<a-button
					v-if="
						[2, 3, 4].includes(invoiceDetails?.approvalStatus) &&
						[0, 2].includes(invoiceDetails?.status) &&
						hasPermissions(['mk_finance_invoicing_history_resubmit']) &&
						!props?.contract?.isApproval
					"
					type="primary"
					@click="submit('resubmit')">
					重新提交
				</a-button>

				<a-button
					v-if="
						[3].includes(invoiceDetails?.approvalStatus) &&
						[1].includes(invoiceDetails?.status) &&
						hasPermissions(['mk_finance_invoicing_history_search']) &&
						!props?.contract?.isApproval
					"
					type="primary"
					@click="submit('queryResults')">
					查询结果
				</a-button>
			</div>
			<!-- 发票推送成功有查询结果  -->

			<!-- 补录发票 -->
			<div v-if="showBlue">
				<a-button v-action="['mk_finance_invoicing_history_update']" @click="recording('edit')">修改</a-button>
				<a-button v-action="['mk_finance_invoicing_history_delete']" type="danger" ghost @click="recording('delete')">删除</a-button>
			</div>
		</template>
	</a-modal>

	<!-- 发票 作废 -->
	<invoice-void-cancel
		v-model:visible="record.approveCancel"
		:id="invoiceDetails?.id"
		@close="record.approveCancel = false"
		@success="emits('close')"></invoice-void-cancel>

	<!--发票--重新提交 and 补录 -->
	<apply-invoice-dialog
		v-model:visible="record.resubmit"
		:resubmitId="resubmitId"
		:id="invoiceDetails?.id"
		:page-type="pageType"
		@success="emits('close')" />

	<!-- 发票撤销 -->
	<invoice-void-revoke
		v-model:visible="record.revoke"
		:invoiceInfoId="invoiceDetails?.id"
		@success="emits('close')"
		@close="record.revoke = false"></invoice-void-revoke>

	<!-- 冲红 重新推送 -->
	<invoice-void-push
		v-model:visible="record.pushAgain"
		:id="invoiceDetails?.id"
		@close="record.pushAgain = false"
		@success="emits('close')"></invoice-void-push>

	<!-- 冲红 --撤销 -->
	<invoice-revoke-flushing
		v-model:visible="record.redCancel"
		:id="invoiceDetails?.id"
		@close="record.redCancel = false"
		@success="emits('close')"></invoice-revoke-flushing>

	<!-- 冲红---重新提交 and 补录 and 修改-->
	<apply-flush-red
		v-model:visible="record.redBlood"
		:invoiceKind="invoiceKind"
		@close="record.redBlood = false"
		:id="invoiceDetails?.id"
		:resubmitId="resubmitId"
		:isSpecialTicket="record.isSpecialTicket"
		:isRecording="pageType === 2"
		:recordingId="recordingId"
		@success="emits('close')"></apply-flush-red>

	<!-- 冲红作废 -->
	<invoiceRevokeRevoke
		v-model:visible="record.redRevoke"
		:id="invoiceDetails?.id"
		@close="record.redRevoke = false"
		@success="emits('close')"></invoiceRevokeRevoke>
</template>

<script setup lang="ts">
	import {onMounted, reactive, ref, watch, toRef, createVNode, computed} from 'vue'
	import {DownloadOutlined, ExclamationCircleOutlined} from '@ant-design/icons-vue'
	import {Modal, message} from 'ant-design-vue'
	import FlushRedInvoceingDetail from '@/components/finance/invoice-administration/billing-history/flush-red-invoceing-detail.vue'
	import {redStatusList} from '@/utils/billing-history-status'
	import {updateQueryResults, invoicingDetails, approvalRevoke, historicalBlueDel, historicalRedDel} from '@/api/invoicing-history'
	import ApplyFlushRed from '@/components/finance/invoice-administration/billing-history/apply-flush-red.vue'
	import FlushRedDetailsApproval from '@/components/finance/invoice-administration/billing-history/flush-red-details-approval.vue'
	import Approval from '@/components/contract/contract-detail-dialog/charter-contract/approve.vue'
	import InvoiceVoidCancel from '@/components/finance/invoice-administration/billing-history/invoice-void-cancel.vue'
	import InvoiceVoidRevoke from '@/components/finance/invoice-administration/billing-history/invoice-void-revoke.vue'
	import InvoiceVoidPush from '@/components/finance/invoice-administration/billing-history/invoice-void-push.vue'
	import InvoiceRevokeFlushing from '@/components/finance/invoice-administration/billing-history/invoice-revoke-flushing.vue'
	import ApplyInvoiceDialog from '@/components/contract/invoice/apply-invoice.vue'
	import {useStore} from '@/store/index'
	const hasPermissions = useStore().hasPermissions

	const props = defineProps<{
		id?: string
		processInstanceId?: string
		visible: boolean
		contract?: {
			businessId?: string
			// 判断是否来源于主应用
			source?: string
			// 判断是否是审批
			isApproval?: boolean
			// 审批模块类型
			approvalType?: string
			// 审批模块
			processInstanceId?: string
			isShow?: boolean
		}
	}>()
	const invoiceKind = ref(1)

	const emits = defineEmits(['update:visible', 'close'])

	const activeKey = ref('flush-red')

	const showInvoicing = ref(true)
	const showRed = ref(true)

	const resubmitId = ref('')

	const recordingId = ref()

	const record = reactive<any>({
		tableList: [
			{
				taxationType: '123456',
				feeSubjectName: '发票类型'
			}
		],
		showInvoice: false,
		approveCancel: false,
		applyFlushRed: false,
		// 判断是普票还是专票
		isSpecialTicket: true,
		pushAgain: false,
		showFooter: true,
		//发票 重新提交
		resubmit: false,
		// 冲红重新提交
		redBlood: false,
		// 发票撤销
		revoke: false,
		// 冲红撤销
		redCancel: false,
		//冲红作废
		redRevoke: false,
		// 重新推送
		queryResults: false
	})
	const invoiceType = ref<any>(1)

	watch(
		() => activeKey.value,
		newVal => {
			if (newVal == 'invoice') {
				record.showInvoice = true
				record.showFooter = false
			} else {
				record.showInvoice = false
				record.showFooter = true
			}
		}
	)

	watch(
		() => props.visible,
		newVal => {
			if (newVal) {
				invoiceType.value = 1
				detailTabs.value = [
					{
						key: 'flush-red',
						value: '冲红详情'
					},
					{
						key: 'invoice',
						value: props?.contract?.isApproval ? '开票详情' : '开票详情'
					}
				]
				getInvoiceDetails(props.id || props?.contract?.businessId)
				activeKey.value = detailTabs.value[0].key
			}
		}
	)

	// 发票详情
	const invoiceDetails = ref<any>({})

	const detailTabs = ref([
		{
			key: 'flush-red',
			value: '冲红详情'
		},
		{
			key: 'invoice',
			value: '开票详情'
		}
	])

	const options = reactive({
		width: 1300,
		centered: true,
		maskClosable: false,
		destroyOnClose: true,
		confirmLoading: true,
		visible: toRef(props, 'visible'),
		onCancel() {
			// emits('close')
			emits('update:visible', false)
			setTimeout(() => emits('close'), 100)
		}
	})

	const confirmLoading = ref<boolean>(false)

	// 关闭
	const close = () => {
		emits('update:visible', false)
		setTimeout(() => emits('close'), 100)
	}
	// 冲红-开票查询结果
	const queryResultsF = (id: string) => {
		updateQueryResults(id).then(() => {
			close()
		})
	}

	//撤销申请
	const submit = (type: string) => {
		// 开票
		resubmitId.value = ''
		record[type] = true
		if (type === 'resubmit') {
			resubmitId.value = invoiceDetails?.value?.id
		} else if (type == 'queryResults') {
			// 查询结果
			queryResultsF(invoiceDetails?.value.id)
		} else if (type === 'revokeApproval') {
			revokeApprovalF()
		}
	}

	//获取发票详情
	const getInvoiceDetails = id => {
		invoicingDetails(id).then((res: any) => {
			invoiceType.value = res.data.invoiceType
			invoiceDetails.value = res.data
			if (invoiceType.value === 1) {
				detailTabs.value.shift()
				// console.log(detailTabs.value)
				activeKey.value = detailTabs.value[0].key
			}
		})
	}

	const handlerClick = (type: string) => {
		resubmitId.value = ''
		// 冲红
		record[type] = true
		invoiceKind.value = invoiceDetails?.value.invoiceKind
		if (type == 'queryResults') {
			// 查询结果
			queryResultsF(invoiceDetails?.value.id)
		} else if (type === 'redBlood') {
			resubmitId.value = invoiceDetails?.value.id
		} else if (type === 'revokeApproval') {
			revokeApprovalF()
		}
	}
	const revokeApprovalF = () => {
		Modal.confirm({
			title: '撤回',
			centered: true,
			icon: createVNode(ExclamationCircleOutlined),
			content: '确定撤回此次审批吗？',
			onOk() {
				confirmLoading.value = true
				return approvalRevoke({
					businessId: invoiceDetails?.value.id
				})
					.then((res: any) => {
						confirmLoading.value = false
						message.success('操作成功')
						emits('close')
					})
					.catch(() => (confirmLoading.value = false))
			}
		})
	}

	const pageType = ref<any>(1)

	const recording = (type: any) => {
		// 红票进入切到开票详情也是删除的红票
		let actionType = invoiceType.value === 2 ? 'flush-red' : activeKey.value
		console.log('🚀 ~ file: flush-red-details.vue:420 ~ recording ~ invoiceType.value:', invoiceType.value)

		if (type === 'edit') {
			pageType.value = 2
			resubmitId.value = invoiceDetails?.value.id

			if (actionType === 'invoice') {
				record.resubmit = true
			}

			if (actionType === 'flush-red') {
				recordingId.value = invoiceDetails?.value.invoiceInfos[0].id
				record.redBlood = true
			}
		}

		if (type === 'delete') {
			let content: any = {
				invoice: '删除后支持对该明细的再次进行开票，确认要删除该开票历史吗?',
				'flush-red': '删除后支持对该发票的再次进行冲红，确认要删除该冲红历史吗?'
			}

			let reqs = {
				invoice: historicalBlueDel,
				'flush-red': historicalRedDel
			}

			Modal.confirm({
				title: '删除',
				icon: createVNode(ExclamationCircleOutlined),
				content: content[actionType],
				onOk() {
					console.log('OK')
					// 调用不同的接口

					reqs[actionType](invoiceDetails?.value.id).then(res => {
						message.success('删除成功')
						emits('update:visible', false)
						setTimeout(() => emits('close'), 100)
					})
				}
			})
		}
	}

	/** 补录操作显示规则 */
	// eslint-disable-next-line vue/return-in-computed-property
	const showBlue = computed(() => {
		if (invoiceType.value === 2) {
			return invoiceDetails.value.sourceType === 1 && activeKey.value === 'flush-red'
		}

		if (invoiceType.value === 1) {
			return invoiceDetails.value.sourceType === 1
		}

		return false
	})
</script>

<style lang="less">
	.ant-descriptions-blockquote {
		display: inline-block;
	}
	.approval-type {
		display: inline-block;
	}
	.icon-font {
		font-size: 14px;
		margin-left: 8px;
	}

	.down-img {
		margin-left: 5px;
		width: 18px;
	}
	.approval-process-list-right {
		min-height: 100%;
		padding-left: 15px;
	}
</style>
